<template>
  <!--完成确认弹窗-->
  <px-dialog v-model="visible" title="完成确认" width="900px" destroy-on-close append-to-body @close="handleCancelAudit">
    <px-form ref="finishRef" :model="formValue" :rules="rules" label-width="120px">
      <px-row>
        <px-col :span="12">
          <px-form-item label="执行人">
            <px-input v-model="name" disabled />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="接单时间">
            <px-input v-model="time" disabled />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="维修完成时间" prop="completionTime">
            <px-date-picker
              v-model="formValue.completionTime"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              :disabled-date="disabledDate"
              placeholder="请选择日期"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="四级主管验收" prop="isSupervised">
            <px-radio-group v-model="formValue.isSupervised" :disabled="taskDetailData.workOrderStatus === 6">
              <px-radio :label="0">无需验收，仅通知</px-radio>
              <px-radio :label="1">需要验收</px-radio>
            </px-radio-group>
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="四级主管" prop="supervisorId">
            <px-select-v2
              v-model="formValue.supervisorId"
              style="width: 100%"
              filterable
              clearable
              :options="approvalList"
              placeholder="请选择四级主管"
              @change="approvalIdChange"
            />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>
    <template #footer>
      <div class="dialog-footer">
        <px-button @click="handleCancelAudit">取 消</px-button>
        <px-button type="primary" @click="handleSubmitAuditForm(finishRef)">确 定</px-button>
      </div>
    </template>
  </px-dialog>
</template>

<script lang="ts" setup>
import { finishMaintain } from "@/api/equip/maintain";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["closeDialog", "handleFinishBack"]);
// 父级传过来的值
const props = defineProps(["visible", "taskDetailData", "tabName"]);

const visible = computed(() => props.visible);

// 表单校验规则
const rules = computed(() => ({
  completionTime: [{ required: true, message: "请选择维修完成时间", trigger: ["blur", "change"] }],
  isSupervised: [{ required: true, message: "请选择是否需要验收", trigger: ["blur", "change"] }],
  supervisorId: [{ required: true, message: "请选择四级主管", trigger: ["blur", "change"] }]
}));

const finishRef = ref();

const state = reactive<Record<string, any>>({
  formValue: {},
  approvalList: [],
  name: "",
  time: ""
});
const { formValue, approvalList, name, time } = toRefs(state);

const handleCancelAudit = () => {
  finishRef.value.resetFields();
  emits("closeDialog");
};

watchEffect(async () => {
  if (props.visible) {
    approvalList.value = await getEmployeeIdAndName();
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    name.value = userInfo.realName;
    time.value = props.taskDetailData.acceptTime;
    formValue.value.isSupervised = props.taskDetailData.isSupervised;
    formValue.value.completionTime = dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss");
  }
});

const disabledDate = (time: Date) => {
  // return time.getTime() > Date.now();
  return dayjs(time.getTime()).isBefore(dayjs(props.taskDetailData.acceptTime)) || dayjs(time.getTime()).isAfter(Date.now());
};

// 获取借用人的名字
const approvalIdChange = val => {
  const arr = approvalList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.supervisorName = arr[0].label;
  }
};
/** 提交按钮 */
const handleSubmitAuditForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      await finishMaintain({ workOrderId: props.taskDetailData.id, ...formValue.value });
      PxMessage.success("完成维修成功");
      handleCancelAudit();
      // 返回主页面
      if (props.tabName) {
        router.push(`/all/equip/maintain/task?tabName=${props.tabName}`);
      } else {
        router.push("/all/message");
      }
    }
  });
};
</script>
